import os
import yaml
import pandas as pd


class FileRoad(object):
    """initialize the file systerm to get file esay

    Args:
        conf_path (str): file-road's type file 
    """
    def __init__(self, conf_path) -> None:
        self.conf = self.__load(conf_path)
        home = os.path.expanduser('~')
        default_conf = os.path.join(home, '.file-road.yaml')
        if os.path.exists(default_conf):
            self.update(default_conf)
        
        current_conf = './file-road.yaml'
        if os.path.exists(current_conf):
            self.update(current_conf)

    def __load(self, conf_path):
        conf = {}
        with open(conf_path, 'r') as f:
            conf = yaml.load(f, yaml.FullLoader)
        return conf

    def update(self, conf_path):
        conf = self.__load(conf_path)
        self.conf.update(conf)

    def get_pth(self, name, tag):
        try:
            file_root = os.path.join(self.conf[name]['root'], name, tag)
            file_path = os.path.join(file_root, self.conf[name][tag]['file'])
            if os.path.exists(file_path):
                return file_path
            else:
                raise FileNotFoundError('The %s file[%s] not in the FileRoad System. Please add it.' % (file_path))
        except:
            raise FileNotFoundError('The %s file not in the FileRoad System. Please add it.' % (file_path))

    def save(self, conf_name):
        save_dict = {"roots": []}
        for index, root in enumerate(self.conf['roots']):
            save_dict['roots'].append('&base%d "%s"' % (index, root))

        for key in self.conf.keys():
            if key == 'roots':
                continue
            save_dict[key] = self.conf[key]
            try:
                index = self.root['roots'].index(self.root[key]['root'])
                save_dict[key]['root'] = '*base%d' % (index)
            except ValueError:
                pass
        
        with open(conf_name, 'w') as f:
            yaml.dump(save_dict, f, default_flow_style=False, indent=2)

    def doc(self, doc_name=None, show=True):
        sort_dict = {"name": [], "tag": [], "desc": []}

        for key in self.conf.keys():
            if key == 'roots':
                continue
            for tag in self.conf[key].keys():
                if tag == 'root':
                    continue
                sort_dict['name'].append(key)
                sort_dict['tag'].append(tag)
                try:
                    sort_dict['desc'].append(self.conf[key][tag]['desc'])
                except:
                    sort_dict['desc'].append('')
        
        df = pd.DataFrame(sort_dict)

        if show:
            print(df)
        
        if doc_name is not None:
            df.to_csv(doc_name, index=False)
